package cn.yuysaln.trigger.job;

import cn.bugstack.middleware.db.router.strategy.IDBRouterStrategy;
import cn.yuysaln.domain.task.model.entity.TaskEntity;
import cn.yuysaln.domain.task.service.ITaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 定时扫描未发送成功的 关于获奖信息的 MQ消息
 */
@Slf4j
@Component
public class SendMessageTaskJob {

    @Resource
    private ITaskService taskService;
    @Resource
    private ThreadPoolExecutor executor;
    @Resource
    private IDBRouterStrategy dbRouter;

    @Scheduled(cron = "*/5 * * * * ?")
    public void exec() {
        try {
            int dbCount = dbRouter.dbCount();
            for (int dbIdx = 1; dbIdx <= dbCount; dbIdx++) {
                int  finalDBIdx = dbIdx;
                executor.execute(() ->{   //并行查询数据库
                    try {
                        dbRouter.setDBKey(finalDBIdx);
                        dbRouter.setTBKey(0);
                        List<TaskEntity> noSentMessage = taskService.queryNoSendMessageTaskList();
                        if (noSentMessage.isEmpty()) return;
                        //重新发送每个任务
                        for (TaskEntity message : noSentMessage) {
                            //多线程加速发送任务
                            executor.execute(() -> {
                                try {
                                    taskService.sendMessage(message);
                                    taskService.updateTaskSendMessageCompleted(message.getUserId(), message.getMessageId());
                                } catch (Exception e) {
                                    log.error("定时任务，发送MQ消息失败 userId: {} topic: {}", message.getUserId(), message.getTopic());
                                    taskService.updateTaskSendMessageFail(message.getUserId(), message.getMessageId());
                                }
                            });
                        }
                    }finally {
                        dbRouter.clear();
                    }
                });
            }
        } catch (Exception e) {
            log.error("定时任务，扫描MQ任务表发送消息失败。", e);
        } finally {
            dbRouter.clear();
        }

    }




}
